const { requestUtil, getBaseUrl } = require('../../utils/requestUtil.js');
const app = getApp();

Page({
  data: {
    typeIndex: 0,
    types: ['功能建议', '界面问题', '其他'],
    content: '',
    info: '',
    feedbackList: [], // 新增反馈列表数据
    baseUrl: '' // 新增baseUrl
  },
  
  onLoad() {
    const baseUrl = getBaseUrl();
    this.setData({
      baseUrl: baseUrl
    });
    this.loadFeedbackList();
  },
  
  onShow() {
    this.loadFeedbackList();
  },
  
  handleTypeChange(e) {
    this.setData({
      typeIndex: e.detail.value
    });
  },
  
  handleFormSubmit(e) {
    const { content, info } = e.detail.value;
    const type = this.data.types[this.data.typeIndex];
    const openid = wx.getStorageSync('openid'); 
    
    if (!content) {
      wx.showToast({
        title: '请填写反馈内容',
        icon: 'none'
      });
      return;
    }
    
    const feedbackData = {
      openid,
      content,
      type,
      info
    };
    
    requestUtil({
      url: '/feedback/submit',
      method: 'POST',
      data: feedbackData
    }).then(res => {
      if (res.code === 0) {
        wx.showToast({
          title: '反馈成功',
          icon: 'success'
        });
        // 清空表单
        this.setData({
          content: '',
          info: ''
        });
        // 刷新反馈列表
        this.loadFeedbackList();
      } else {
        wx.showToast({
          title: '反馈失败，请重试',
          icon: 'none'
        });
      }
    }).catch(err => {
      wx.showToast({
        title: '反馈失败，请检查网络',
        icon: 'none'
      });
    });
  },
  
  // 加载反馈列表方法（使用async/await和统一的时间格式化）
  async loadFeedbackList() {
    try {
      const openid = wx.getStorageSync('openid');
      if (!openid) return;
      
      const result = await requestUtil({
        url: '/feedback/list',
        method: 'GET',
        data: { openid }
      });
      
      if (result.code === 0) {
        // 格式化时间，与你提供的代码保持一致
        const feedbackList = result.data.map(item => ({
          ...item,
          vtime: this.formatTime(new Date(item.vtime))
        }));
        
        this.setData({
          feedbackList: feedbackList || []
        });
      } else {
        console.error('获取反馈列表失败', result.message);
      }
    } catch (error) {
      console.error('获取反馈列表失败', error);
    }
  },
  
  // 时间格式化方法
  formatTime(date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hour = String(date.getHours()).padStart(2, '0');
    const minute = String(date.getMinutes()).padStart(2, '0');
    return `${year}-${month}-${day} ${hour}:${minute}`;
  }
});